package com.authine.cloudpivot.ext.controller;

import com.authine.cloudpivot.engine.api.model.bizmodel.FilterModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.type.DefaultPropertyType;
import com.authine.cloudpivot.engine.enums.type.OperatorType;
import com.authine.cloudpivot.web.api.controller.runtime.QueryRuntimeController;
import com.authine.cloudpivot.web.api.handler.CustomizedOrigin;
import com.authine.cloudpivot.web.api.view.PageVO;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.authine.cloudpivot.web.api.view.runtime.QueryDataVO;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


/**
 * 定制列表查询功能Controller.
 */
@Api(tags = "运行时::列表::定制列表查询")
@RestController
@RequestMapping("/api/runtime/query")
@Slf4j
@CustomizedOrigin(level = 1)
public class CustomizedQueryRuntimeController extends QueryRuntimeController {

    /**
     * 列表查询方法
     * 如果需要定制查询方法，
     * 需要将QueryDataVO.customized设置为true
     * （即前端接口参数中将需要将QueryDataVO.customized设置为true）
     *
     * @param queryData 查询对象
     * @return page
     */
    @ApiOperation(value = "查询数据接口")
    @PostMapping("/list")
    @Override
    public ResponseResult<PageVO<BizObjectModel>> list(@RequestBody QueryDataVO queryData) {
        if (log.isDebugEnabled()) {
            log.debug("query list.customized = [{}]", queryData.isCustomized());
        }
        if (queryData.getQueryVersion() == null) {
            if (!queryData.isCustomized()) {         // 默认执行云枢产品列表查询方法
                log.info("执行云枢产品列表查询方法");
                if(queryData.getReverseSchemaParam() != null){
                    // 获取所有系统字段（排除掉系统字段，单据号查询时会出现分号分隔的情况，如：PROCESSING;COMPLETED，直接设置为op查询会查不到数据）
                    List<String> systemPropertyList = Lists.newArrayList();
                    DefaultPropertyType[] values = DefaultPropertyType.values();
                    for (DefaultPropertyType defaultPropertyType :values) {
                        systemPropertyList.add(defaultPropertyType.getCode());
                    }
                    List<FilterModel> filters = queryData.getFilters();
                    for (FilterModel filter : filters) {
                        if (!systemPropertyList.contains(filter.getPropertyCode()) && filter.getPropertyType().getIndex() == 0 && filter.getOperatorType() == null && StringUtils.isNotEmpty(filter.getPropertyValue())) {
                            filter.setOperatorType(OperatorType.EQ);
                        }
                    }
                };
                return super.list(queryData);
            } else {                                 //二次开发定制列表查询
                log.info("执行二次开发定制列表查询");
                return doCustomizedList(queryData);
            }
        } else {
            return super.list(queryData);
        }
    }

    private ResponseResult<PageVO<BizObjectModel>> doCustomizedList(QueryDataVO queryData) {
        // TODO 二次开发定制列表查询
        // 如果需要定制列表查询方法，请在此处添加具体的实现
        // queryData.getSchemaCode() 数据模型编码
        // queryData.getQueryCode()  列表查询编码
        // 例： 自定义 模型编码schemaCode=test01, 列表查询编码queryCode=qu01 的查询方法
        // 则可以:
        if (log.isDebugEnabled()) {
            log.debug("二次开发代码.");
        }


        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setQueryCode(queryData.getQueryCode());
        queryModel.setSchemaCode(queryData.getSchemaCode());
        queryModel.setPageable(new PageableImpl(queryData.getPage(), queryData.getSize()));
        queryModel.setOptions(queryData.getOptions());
        List<FilterModel> filters = queryData.getFilters();
        List<FilterExpression> list = new ArrayList<>();
        filters.forEach(f->list.add(Q.it(f.getPropertyCode(), FilterExpression.Op.Eq,f.getPropertyValue())));
        if(list.size()==1){
            queryModel.setFilterExpr(list.get(0));
        }else if(list.size()>1){
            queryModel.setFilterExpr(Q.and(list));
        }
        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        return this.getOkResponseResult(new PageVO<>(page), "获取数据成功");
    }
}
